﻿Ext.define('Ext.ux.PicManager', {
    extend: 'Ext.container.Container',
    alias: 'widget.picmanager',
    layout: 'border',
    //requires: ["Ext.ux.DataView.DragSelector"],
    //requires: ['WeCompany.model.File', 'WeCompany.model.Folder'],
    initComponent: function () {
        var me = this;

        Ext.define('File', {
            extend: 'Ext.data.Model',
            fields: ['filename', 'path', 'modify',
                { name: 'size', type: 'int' }
            ]
        });

        Ext.define('Folder', {
            extend: 'Ext.data.Model',
            fields: ['id', 'text', 'parentId'],
            //验证项,目录名不能为空
            validations: [{
                type: 'presence',
                field: 'text'
            }],
            proxy: {
                type: 'ajax',
                api: {
                    create: 'Folder/Create',  //新增
                    read: 'Folder/LoadAll',    //读取
                    destroy: 'Folder/Remove',  //删除
                    update: 'Folder/Update' //修改
                }, reader: {
                    type: 'json',
                    root: 'data',
                    messageProperty: 'Msg'
                }, writer: {
                    type: 'json',
                    root: 'data',
                    encode: true,
                    allowSingle: true
                }, listeners: {
                    //exception:function()
                }
            }
        });

        me.treeStore = Ext.create('Ext.data.TreeStore', {
            root: {
                id: '/',                //根节点的id使用“/”，是为了方便后台将虚拟路径转换为实际路径。
                text: '根目录',
                expanded: true
            },
            model: 'Folder'
        });

        me.tree = Ext.widget('treepanel', {
            title: '文件目录',
            region: 'west',
            collapsible: true,
            rootVisible: true,
            width: 250,
            minWidth: 200,
            maxWidth: 300,
            split: true,
            hideHeaders: true, //
            plugins: [{
                ptype: 'cellediting',
                //插件的监听事件
                listeners: {
                    beforeedit: function (edit, e) {
                        if (e.record.isRoot())
                            return false;
                    },
                    edit: function (edit, e) {
                        e.record.save({
                            success: function (rec, opt) {
                                opt.records[0].setId(opt.records[0].data.parentId + opt.records[0].data.text + "/");
                                opt.records[0].commit();
                            },
                            failure: function (e, opt) {
                                op.records[0].reject();
                                Ext.Msg.alert("发生错误", op.error);
                            }
                        });
                    }
                }
            }],
            columns: [{
                xtype: 'treecolumn',
                dataIndex: 'text',
                flex: 1,
                field: {
                    alloBank: false,
                    selectOnFocus: true
                }
            }],
            viewConfig: {
                toggleOnDblClick: false
            },
            tbar: [{
                iconCls: "folder-add",
                handler: me.onAddFolder,
                scope: me,
                tooltip: "添加目录"
            }, {
                iconCls: "folder-delete",
                handler: me.onDeleteFolder,
                scope: me,
                disabled: true,
                tooltip: "删除目录"
            }, {
                iconCls: "refresh",
                handler: me.onRefreshFolder,
                scope: me,
                tooltip: "刷新目录树"
            }],
            listeners: {
                scope: me,
                //默认选择第一个根目录
                viewready: function (panel) {
                    var view = panel.getView();
                    view.getSelectionModel().select(0);
                },

                //选择任意一个节点显示删除节点
                selectionchange: function (model, sels) {
                    var me = this;
                    if (sels.length > 0) {
                        var rs = sels[0],
                        store = me.filestore;
                        store.proxy.extraParams.path = rs.data.id;
                        store.loadPage(1);
                    }
                    me.tree.down("button[tooltip=删除目录]").setDisabled(sels.length == 0);
                }

            },
            store: me.treeStore
        });

        me.filestore = Ext.create('Ext.data.Store', {
            batchActions: false,                //禁止批量提交
            remoteFilter: false,                 //在客户端进行延迟操作
            remoteSort: true,                   //在客户端排序|远程排序
            pageSize: 50,
            model: 'File',
            sorters: {
                property: 'modify',
                direction: 'DESC',
                allowSingle: true
            },
            proxy: {
                type: 'ajax',
                api: {
                    read: 'File/LoadPageFiles',
                    destroy: 'File/Romove'
                }, reader: {
                    type: 'json',
                    root: 'data'
                }, writer: {
                    type: 'json',
                    root: 'data',
                    encode: true,
                    allowSingle: false
                }, listeners: {
                    //exception:
                }
            }
        });

        me.dataview = Ext.widget("dataview", {
            store: me.filestore,
            autoScroll: true,
            multiSelect: true,
            selectedItemCls: "selected",
            itemSelector: 'div.imageList',
            overItemCls: "overitem",
            trackOver: true,
            tpl: [
                '<tpl for=".">',
                    '<div class="imageList">',
                        '<img width="160" height="160"src="../Thumbnail{path}{filename}?width=160&height=160"data-qtip="文件名：{filename}<br/>修改日期：{modify}<br>大小：{size:this.filesize}"/><br/>',
                        '<p class="ellipsis">{filename}</p>',
                    '</div>',
                '</tpl>',
                '<div class="x-clear"></div>',
                 {
                     filesize: function (size) {
                         if (size < 1024) {
                             return v + " 字节";
                         } else if (size < 1048576) {
                             return (Math.round(((size * 10) / 1024)) / 10) + " KB";
                         } else {
                             return (Math.round(((size * 10) / 1048576)) / 10) + " MB";
                         }
                     }
                 }
            ],
            plugins: [Ext.create('Ext.ux.DataView.DragSelector', {})],
            listeners: {
                scope: me,
                selectionchange: me.onPictureSelect
            }
        });

        me.progress = Ext.widget('progressbar', {
            text: '上传进度',
            flex: 1
        });

        me.spanid = Ext.id();

        me.items = [
            me.tree,
            {
                title: "图片文件",
                region: "center",
                layout: 'fit',
                items: [me.dataview],
                dockedItems: [{
                    xtype: "toolbar",
                    dock: "bottom",
                    items: [
                        { xtype: "tbtext", text: "<span id='" + me.spanid + "'></span>", width: 70 },
                        me.progress
                    ]
                }],
                tbar: {
                    xtype: "pagingtoolbar",
                    pageSize: 20,
                    displayInfo: true,
                    store: me.filestore,
                    items: ['-',
                        {
                            xtype: "splitbutton",
                            iconCls: "sort",
                            tooltip: "排序",
                            text: "排序",
                            scope: me,
                            menu: {
                                items: [{
                                    text: '文件名顺序',
                                    group: 'sort',
                                    checked: false,
                                    checkHandler: me.onSort,
                                    scope: me,
                                    fieldname: "filename",
                                    sortdir: "ASC"
                                }, {
                                    text: '文件名降序',
                                    group: 'sort',
                                    checked: false,
                                    checkHandler: me.onSort,
                                    scope: me,
                                    fieldname: "filename",
                                    sortdir: "DESC"
                                }, {
                                    text: '修改日期顺序',
                                    group: 'sort',
                                    checked: false,
                                    checkHandler: me.onSort,
                                    scope: me,
                                    fieldname: "modify",
                                    sortdir: "ASC"
                                }, {
                                    text: '修改日期降序',
                                    checked: true,
                                    group: 'sort',
                                    checkHandler: me.onSort,
                                    scope: me,
                                    fieldname: "modify",
                                    sortdir: "DESC"
                                }, {
                                    text: '文件大小顺序',
                                    group: 'sort',
                                    checked: false,
                                    checkHandler: me.onSort,
                                    scope: me,
                                    fieldname: "size",
                                    sortdir: "ASC"
                                }, {
                                    text: '文件大小降序',
                                    group: 'sort',
                                    checked: false,
                                    checkHandler: me.onSort,
                                    scope: me,
                                }]
                            }
                        },
                        {
                            iconCls: "picture-delete",
                            handler: me.onDelete,
                            scope: me,
                            disabled: true,
                            text: '删除',
                            tooltip: "删除图片"
                        }
                    ]
                }
            }

        ];
        me.on("afterrender", me.onAfterRender);

        me.callParent(arguments);
    },
    //创建目录
    onAddFolder: function () {

        var tree = this.tree,
			parent = tree.getSelectionModel().getSelection()[0];
        if (!parent) {
            parent = tree.getRootNode();
        }
        //创建目录
        var rec = new Folder({
            text: "新建文件夹",
            id: "",
            parentId: parent.data.id
        });
        //保存
        rec.save({
            url: "Folder/Create",
            parentNode: parent,
            success: function (rec, opt) {
                if (opt.parentNode.isExpanded())
                    opt.parentNode.appendChild(rec);
                else
                    opt.parentNode.expand();
            },
            //failure: SimpleCMS.ModelException,
            scope: tree
        });
    },

    onDeleteFolder: function () {
        var me = this,
            tree = me.tree,
            rs = tree.getSelectionModel().getSelection();
        if (rs.length > 0) {
            rs = rs[0];
            if (rs.data.root) {
                Ext.Msg.alert("删除文件夹", "根目录不允许删除！");
                return;
            }
            var content = "确定删除目录“" + rs.data.text + "”？<br/><p style='color:red'>注意：目录下的文件及子目录都会被删除。</p>";
            Ext.Msg.confirm("删除目录", content, function (btn) {
                if (btn == "yes") {
                    var rs = this.getSelectionModel().getSelection();
                    if (rs.length > 0) {
                        rs = rs[0];
                        rs.remove();
                        this.store.sync({
                            success: function (e, opt) {
                                var me = this;
                                me.store.commitChanges();
                                me.view.select(0);
                                me.view.focus(false);
                            },
                            failure: SimpleCMS.ModelException,
                            scope: tree
                        });
                    }
                }
            }, tree)
        }
    },

    onSort: function (item, checked) {
        var me = this;
        if (checked) {
            me.filestore.sort({ property: item.fieldname, direction: item.sortdir });
            me.filestore.load();
        }
    },

    onPictureSelect: function (model, sels) {
        this.down("button[tooltip=删除图片]").setDisabled(sels.length == 0);
    },

    onDelete: function () {
        var me = this,
            rs = me.dataview.getSelectionModel().getSelection();//获取选择的
        if (rs.length > 0) {
            content = ["确定删除以下图片？"];
            for (var i = 0; ln = rs.length, i < ln; i++) {
                content.push(rs[i].data.filename);
            }
            Ext.Msg.confirm('删除图片', content.join("<br/>"), function (btn) {
                if (btn == 'yes') {
                    var me = this,
                        store = me.dataview.store;
                    rs = me.dataview.getSelectionModel().getSelection();
                    store.remove(rs);
                    store.sync({
                        success: function (e, opt) {
                            this.store.commitChanges();
                        },
                        failure: function (e, opt) {
                            this.store.rejectChanges();
                            Ext.Msg.alert("发生错误", e.exceptions[0].error);
                        },
                        scope: me.dataview
                    });
                }
            }, me);
        } else {
            Ext.Msg.alert('删除记录', '请选择要删除的记录。');
        }

    },

    onAfterRender: function () {
        var me = this;

        me.swfu = new SWFUpload({
            upload_url: "/File/Upload",
            file_size_limit: "10 MB",
            file_types: "*.jpg;*.png;*.gif;*.bmp;",
            file_types_description: "图片文件",
            file_upload_limit: 100,
            file_queue_limit: 0,
            file_post_name: "Filedata",
            swfupload_preload_handler: me.UploadPreLoad,
            swfupload_load_failed_handler: me.UploadLoadFailed,
            swfupload_loaded_handler: me.UploadLoaded,
            file_queued_handler: me.fileQueued,
            file_queue_error_handler: me.fileQueueError,
            file_dialog_complete_handler: me.fileDialogComplete,
            upload_start_handler: me.uploadStart,
            upload_progress_handler: me.uploadProgress,
            upload_error_handler: me.uploadError,
            upload_success_handler: me.uploadSuccess,
            upload_complete_handler: me.uploadComplete,
            queue_complete_handler: me.queueComplete,
            // Button settings
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            button_image_url: '',
            button_placeholder_id: me.spanid,
            button_width: 60,
            button_height: 20,
            button_text: '上传图片',
            button_text_style: '',
            button_text_top_padding: 0,
            button_text_left_padding: 0,
            // Flash Settings
            flash_url: "Scripts/swfupload/swfupload.swf", // Relative to this file
            flash9_url: "Scripts/swfupload/swfupload_FP9.swf", // Relative to this file
            custom_settings: { scope: me },
            // Debug Settings
            debug: false
        });
    },

    UploadPreLoad: function () {
    },

    UploadLoadFailed: function () {
    },

    UploadLoaded: function () {

    },

    fileQueued: function () {
    },

    fileQueueError: function (file, errorCode, message) {
        try {
            var dlg = Ext.Msg.alert;
            if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
                dlg("选择的文件太多。\n一次最多上传100个文件，而你选择了" + message + "个文件。");
                return;
            }
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    dlg("文件超过了10M.");
                    this.debug("错误代码: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    dlg("不允许上传0字节文件。");
                    this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    dlg("非法的文件类型。");
                    this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                default:
                    if (file !== null) {
                        dlg("未知错误。");
                    }
                    this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
            }
        } catch (ex) {
            this.debug(ex);
        }
    },

    fileDialogComplete: function (numFilesSelected, numFilesQueued) {
        try {
            if (numFilesQueued > 0) {
                var me = this.customSettings.scope,
                    //然后从树中获取选择模型，看是否有选择节点，如果有，就把选择节点（目录）作为上传路径，否则，提示用户选择一个节点（目录）
                    sels = me.tree.getSelectionModel().getSelection(), path = "/";
                if (sels.length > 0) {
                    path = sels[0].data.id;
                    //Flash上传并不会把当前页面的验证作为其验证，因而要在服务器端验证上传文件的用户是否已经登录且符合权限要求，就要求通过添加验证方式办法来实现
                    WeCompany.postParams.path = path;
                    this.setPostParams(WeCompany.postParams);
                    //开始上传
                    this.startUpload();
                }
                else {
                    Ext.Msg.alert("请先选择文件夹。");
                }
            }
        } catch (ex) {
            this.debug(ex);
        }
    },

    uploadStart: function (file) {
        try {
            var me = this.customSettings.scope;
            me.progress.updateProgress(0);
            me.progress.updateText("正在上传文件" + file.name + "...");
        }
        catch (ex) { }

        return true;
    },

    uploadProgress: function (file, bytesLoaded, bytesTotal) {
        try {
            var percent = bytesLoaded / bytesTotal;
            var me = this.customSettings.scope;
            me.progress.updateProgress(percent);
            me.progress.updateText("正在上传文件" + file.name + "...");
        } catch (ex) {
            this.debug(ex);
        }
    },

    uploadError: function (file, errorCode, message) {
        try {
            var me = this.customSettings.scope;
            me.progress.updateText("正在上传文件" + file.name + "...");
            switch (errorCode) {
                case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                    me.progress.updateText("上传错误：" + message);
                    this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                    me.progress.updateText("上传失败。");
                    this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    me.progress.updateText("Server (IO) 错误");
                    this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                    me.progress.updateText("安全错误");
                    this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                    me.progress.updateText("文件大小超出限制。");
                    this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                    me.progress.updateText("验证失败。");
                    this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
                case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                    me.progress.updateText("停止");
                    break;
                default:
                    me.progress.updateText("未知错误：" + errorCode);
                    this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                    break;
            }
        } catch (ex) {
            this.debug(ex);
        }
    },

    uploadSuccess: function (file, serverData) {
        try {
            var me = this.customSettings.scope;
            me.progress.updateProgress(1);
            me.progress.updateText(serverData);

        } catch (ex) {
            this.debug(ex);
        }
    },

    uploadComplete: function (file) {
        try {
            if (this.getStats().files_queued > 0) {
                this.startUpload();
            } else {
                var me = this.customSettings.scope;
                me.progress.updateProgress(1);
                me.progress.updateText("所有文件已上传。");
                me.filestore.load();
            }
        } catch (ex) {
            this.debug(ex);
        }
    },

    queueComplete: function (numFilesUploaded) {
        var me = this.customSettings.scope;
        me.progress.updateProgress(1);
        me.progress.updateText("已上传" + numFilesUploaded + "个文件");
        if (numFilesUploaded > 0) {
            me.filestore.load();
        }
    },
    onRefreshFolder: function () {
        this.tree.store.load();
    }
});